/**
 * Created by wenguangjia on 2017/5/9.
 */
(function () {
    'use strict';

    angular
        .module('logcenterApp')
        .controller('svcConsoleController', svcConsoleController);
    svcConsoleController.$inject = ['$scope', '$rootScope', 'searchService','$stateParams'];
    function svcConsoleController($scope, $rootScope, searchService,$stateParams) {
        $scope.isRepeat2=true;
        $scope.isRepeat = false;
        var isUp = false;
        var upStop = false;
        var upPageCount = 0;
        var downPageCount = 0;
        var downSize = 30;
        $scope.upSize = 5;
        var array = new Array();//数据源
        var upArray = new Array();//重复数据源
        var downArray = new Array();//重复数据源
        var isLoadMore = true;//如果为false则不自动加载
        var serviceEndFlag="";//如果倒序，获取endFlag
        var data = {
            "query": {
                "bool": {
                    "must": [],
                    "filter": []
                }
            },
            "sort": [{
                "@timestamp": {
                    "order": "asc"
                }
            },{
                "flag": {
                    "order": "asc"
                }
            }],
            "size": downSize,
            "from": downPageCount
         };
        var serviceObj;
        if ($stateParams.completelyLog)
            serviceObj = JSON.parse($stateParams.completelyLog);
        var type=serviceObj.searchType;
        if(type == 3){$scope.fileNameSearch=true;}
        var obj = {"term": {"file_name": serviceObj.fileName}};
        data.query.bool.filter.push(obj);
        var obj = {"term": {"partition": serviceObj.partition}};
        data.query.bool.filter.push(obj);
        // var obj = {"range": {"@timestamp": {"gte": serviceObj['@timestamp']}}};
        var flag=serviceObj.flag;
        if (serviceObj.logmsg && serviceObj.logmsg.indexOf("1. service begin")!=-1) {
            if(serviceObj.debug){
                serviceObj.flag=serviceObj.flag+1;
                flag = serviceObj.flag;
            }
            upStop = true;
        }else{
            if(serviceObj.searchType != 3){
                serviceObj.flag=serviceObj.flag-6;
            }else{
                serviceObj.flag=serviceObj.flag-20;
            }
        }
        var obj = {"range": {"flag": {"gte": serviceObj.flag}}};
        data.query.bool.filter.push(obj);

        /**
         * 倒序和全部查询处理
         */
        if(serviceObj.searchType == 1 || serviceObj.searchType == 2){
            var maxFlag=0;
            //如果此service是最后一次调用，查找此文件下最大flag
            var max = {
                "query": {
                    "bool": {
                        "filter": [
                            {"term":{"file_name":serviceObj.fileName}},
                            {"term":{"partition":serviceObj.partition}}
                        ]
                    }
                },
                "aggs" : {
                    "max_flag" : { "max" : { "field" : "flag" } }
                },
                "size": 1,
                "from": 0
            };
            console.log("max:"+JSON.stringify(max));
            searchService.query(max,null,'service').then(function (resp) {
                maxFlag = resp.data.aggregations.max_flag.value;
                //查找比此履历往后的service begin
                var data2={
                    "query": {
                        "bool": {
                            "must": [{
                                "match_phrase": {
                                    "logmsg": "1. service begin"
                                }}
                            ],
                            "filter": [
                                {"term":{"file_name":serviceObj.fileName}},
                                {"term":{"partition":serviceObj.partition}},
                                {"range": {"flag": {"gt": serviceObj.flag+1}}}
                            ]
                        }
                    },
                    "sort": [{
                        "@timestamp": {
                            "order": "asc"
                        }
                    },{
                        "flag": {
                            "order": "asc"
                        }
                    }],
                    "size": 1,
                    "from": 0
                };
                console.log(JSON.stringify(data2));
                searchService.query(data2,null,'service').then(function (resp) {
                    type=4;
                    var gte = serviceObj.flag;
                    if(resp.data.hits.hits.length>0){
                        //查找此履历最后一条的flag
                        var end = {
                            "query": {
                                "bool": {
                                    "filter": [
                                        {"term":{"file_name":serviceObj.fileName}},
                                        {"term":{"partition":serviceObj.partition}},
                                        {"range":{"flag":{"lt":resp.data.hits.hits[0]._source.flag}}}
                                    ]
                                }
                            },
                            "sort": [{
                                "@timestamp": {
                                    "order": "desc"
                                }
                            },{
                                "flag": {
                                    "order": "desc"
                                }
                            }],
                            "size": 1,
                            "from": 0
                        };
                        console.log("end:"+JSON.stringify(end));
                        searchService.query(end,null,'service').then(function (resp) {
                            serviceEndFlag = resp.data.hits.hits[0]._source.flag;
                            configData(serviceEndFlag);
                        },function(error){console.log(error)});
                    }else{
                        serviceEndFlag = maxFlag;
                        configData(serviceEndFlag);
                    }
                },function(error){
                    console.log(error);
                })
            },function(error){
             console.log(error);
            });
        }

        function configData(serviceEndFlag){
            var gte = serviceObj.flag;
            if(serviceObj.searchType==2){
                data.size=6000;
                upStop=true;
                isLoadMore=false;
            }else{
                var temp = serviceEndFlag-serviceObj.flag;
                if(temp>20){
                    upStop = false;
                    gte = serviceEndFlag-20;
                }else{
                    upStop = true;
                }
            }
            data.query.bool.filter[2]  = {"range": {"flag": {"gte":gte,"lte": serviceEndFlag}}};
            $scope.ELKGridOptions.dataSource.read();
        }



        //文档高度
        function getDocumentTop() {
            var scrollTop = 0, bodyScrollTop = 0, documentScrollTop = 0;
            if (document.body) {
                bodyScrollTop = document.body.scrollTop;
            }
            if (document.documentElement) {
                // 上翻后会出现小数，文档高度向上取整
                documentScrollTop = Math.ceil(document.documentElement.scrollTop);
            }
            scrollTop = (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop;
            return scrollTop;
        }

        //可视窗口高度
        function getWindowHeight() {
            var windowHeight = 0;
            if (document.compatMode == "CSS1Compat") {
                windowHeight = document.documentElement.clientHeight;
            } else {
                windowHeight = document.body.clientHeight;
            }
            return windowHeight;
        }

        //滚动条滚动高度
        function getScrollHeight() {
            var scrollHeight = 0, bodyScrollHeight = 0, documentScrollHeight = 0;
            if (document.body) {
                bodyScrollHeight = document.body.scrollHeight;
            }
            if (document.documentElement) {
                documentScrollHeight = document.documentElement.scrollHeight;
            }
            scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight;
            return scrollHeight;
        }

        window.onscroll = function () {
            //监听事件内容
            if(serviceObj.searchType == 3 && !isLoadMore){
                isLoadMore = true;
            }
            if ((getDocumentTop() + getWindowHeight() == getScrollHeight()) && isLoadMore) {
                //当滚动条到底时,这里是触发内容
                //异步请求数据,局部刷新dom
                //requestData.from+=sourceCount;
                isUp = false;
                //是否倒序
                if(serviceObj.searchType == 1){
                    data.query.bool.filter[2] = {"range": {"flag": {"lte": serviceEndFlag}}};
                    data.sort[1].flag.order = "desc";
                    data.sort[0]['@timestamp'].order = "desc";
                }else{
                    data.query.bool.filter[2] = {"range": {"flag": {"gte": serviceObj.flag}}};
                    data.sort[1].flag.order = "asc";
                    data.sort[0]['@timestamp'].order = "asc";
                }
                downPageCount += downSize;
                data.from = downPageCount;
                data.size = downSize;
                $scope.ELKGridOptions.dataSource.read();
            }
        }

        $scope.upLoad = function () {
            if(serviceObj.searchType == 3 && upStop){
                upStop=false;
            }
            if (!upStop) {
                isUp = true;
                if(serviceEndFlag==""){
                    data.query.bool.filter[2] = {"range": {"flag": {"lt": serviceObj.flag}}};
                    data.query.bool.filter[3] = {"range":{"@timestamp":{"lt":serviceObj["@timestamp"]}}}
                }else{
                    data.query.bool.filter[2] = {"range": {"flag": {"lt": serviceEndFlag-20}}};
                }
                data.sort[0]['@timestamp'].order = "desc";
                data.sort[1].flag.order = "desc";
                data.from = upPageCount;
                upPageCount += $scope.upSize;
                data.size = $scope.upSize;
                $scope.ELKGridOptions.dataSource.read();
            }
        };

        /**
         * grid
         * @type {*[]}
         */
        var prioritys = [{text: "TRACE", value: "1"}, {text: "DEBUG", value: "2"}, {
            text: "INFO",
            value: "3"
        }, {text: "WARN", value: "4"}, {text: "ERROR", value: "5"}, {text: "CRITICAL", value: "6"}];
        var columns = [
            {
                field: "",
                title: "序号",
                template: function () {
                    return ++$scope.rowNumber;
                },
                width: "50px"
            },
            {field: "sourceId", hidden: true},
            {field: "partition", title: "分区", width: "80px"},
            {field: "timestamp", title: "生成时间", format: "{0: yyyy-MM-dd HH:mm:ss:fff}", width: "180px"},
            {
                field: "logmsg", title: "日志消息", width: "300px",
                template: function (dataItem) {
                    var result = "";
                    // if(dataItem.logmsg==serviceObj.logmsg){
                    if (dataItem.sourceId == serviceObj.id ||
                        (dataItem.logmsg== serviceObj.logmsg &&
                            dataItem["@timestamp"] == serviceObj["@timestamp"])) {
                        result = '<span style="color: red">{{dataItem.logmsg}}</span>'
                    } else {
                        result = '<span style="color: black">{{dataItem.logmsg}}</span>'
                    }
                    return result;
                }
            },
            {field: "key1", title: "关键字1", width: "100px"},
            {field: "key2", title: "关键字2", width: "100px", hidden: true},
            {field: "key3", title: "关键字3", width: "100px", hidden: true},
            {field: "key4", title: "关键字4", width: "100px", hidden: true},
            {field: "key5", title: "关键字5", width: "100px", hidden: true},
            {field: "priority", title: "级别", width: "80px", values: prioritys, hidden: true},
            {field: "category", title: "类别", width: "150px", hidden: true},
            {field: "interval", title: "间隔时间", width: "150px", hidden: true},
            {field: "pid", title: "进程号", width: "150px", hidden: true},
            {field: "ip", title: "IP地址", width: "150px", hidden: true},
            {field: "mac", title: "MAC地址", width: "150px", hidden: true},
            {field: "username", title: "用户名", width: "100px"},
            {field: "formname", title: "画面名", width: "100px"},
            {field: "svc", title: "服务名", width: "130px"},
            {field: "func", title: "函数名", width: "150px", hidden: true},
        ];

        $scope.ELKGridOptions = {
            selectable: "row",
            scrollable: true,
            sortable: true,
            resizable: true,
            columns: columns,
            columnMenu: true,
            dataBound: function(e) {
                $scope.rowNumber = 0;
            }
        };
        $scope.ELKModel = kendo.data.Model.define({
            id: "sourceId",
            fields: {
                timestamp: {validation: {required: true}, type: 'date'},
            }
        });
        $scope.ELKGridOptions.dataSource = new kendo.data.DataSource({
            autoBind: false,
            transport: {
                read: function (e) {
                    console.log(JSON.stringify(data));
                    searchService.query(data,null,'service').then(function (resp) {
                        console.log(resp);
                        $scope.rowNumber = 0;
                        var data = resp.data.hits.hits;
                        if(data.length==6000){
                            alert("日志履历大于6000条，只显示6000条");
                        }
                        if(data.length==0 && serviceObj.searchType == 3){
                                // var scrollHeight = 0, bodyScrollHeight = 0, documentScrollHeight = 0;
                                // if (document.body) {
                                //     bodyScrollHeight = document.body.scrollHeight;
                                // }
                                // if (document.documentElement) {
                                //     documentScrollHeight = document.documentElement.scrollHeight;
                                // }
                                // scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight;
                                // window.scrollTo(0,scrollHeight-10);
                            if(isUp){
                                upPageCount -= $scope.upSize;
                            }else{
                                downPageCount -= downSize;
                            }
                        }
                        var upLoad = false;
                        var downLoad = false;
                        if (!isUp) {
                            data.length == downSize ? isLoadMore = true : isLoadMore = false;
                            if($scope.isRepeat){
                                array = array.concat(downArray);
                                downArray.length = 0;
                            }
                        } else {
                            data.length == $scope.upSize ? upStop = false : upStop = true;
                            if($scope.isRepeat){
                                array = upArray.concat(array);
                                upArray.length = 0;
                            }
                        }
                        angular.forEach(data, function (item) {
                            // if (!stop) {
                            item._source.username = item._source.uid;
                            item._source.timestamp = item._source['@timestamp'];
                            item._source.sourceId = item._id;

                            if (!item._source.logmsg) {
                                item._source.logmsg = "";
                            }

                            if (isUp) {
                                upLoad ? upArray.unshift(item._source) : array.unshift(item._source);
                                // array.unshift(item._source);
                                if (serviceObj.searchType != 3 && item._source.logmsg.indexOf("1. service begin") != -1 && !$scope.isRepeat) {
                                        upStop = true;
                                        upLoad = true;
                                }
                            } else {
                                if(serviceObj.searchType == 3){
                                    downLoad ? downArray.push(item._source) : array.push(item._source);
                                }
                                if (serviceObj.searchType != 3 && !(item._source.logmsg.indexOf("service end") != -1 && !$scope.isRepeat&& item._source.flag<flag)) {

                                    if (item._source.logmsg.indexOf("1. service begin") != -1 && !$scope.isRepeat&& item._source.flag>(flag +1)) {
                                        downLoad = true;
                                        isLoadMore = false;
                                    }
                                    downLoad ? downArray.push(item._source) : array.push(item._source);
                                    if (item._source.logmsg.indexOf("1. service begin") != -1 && !$scope.isRepeat&& item._source.flag<flag) {
                                        upStop = true;
                                        upLoad = true;
                                    }
                                }
                            // }
                             }
                            //
                        });
                        e.success(array);
                    }, function (error) {
                        e.error(error)
                    });
                },
                parameterMap: function (options, operation) {
                    if (operation !== "read" && options.models) {
                        return {models: kendo.stringify(options.models)};
                    }
                }
            },
            requestStart: function (e) {
                if (type==1 || type==2) {
                    e.preventDefault();
                }
            },
            schema: {
                model: $scope.ELKModel
            }
        });

        // $scope.loadMore = function () {
        //     isUp = false;
        //     data.query.bool.filter[2] = {"range": {"flag": {"gte": serviceObj.flag}}};
        //     data.sort['flag'].order = "asc";
        //     downPageCount += downSize;
        //     data.from = downPageCount;
        //     data.size = downSize;
        //     $scope.ELKGridOptions.dataSource.read();
        // };
        $scope.select = function () {
            $scope.isRepeat2?$scope.isRepeat=false:$scope.isRepeat=true;
            data.query.bool.filter[3] = {};
            if ($scope.isRepeat) {
                upStop = false;
                isLoadMore = true;
                isUp = false;
                data.query.bool.filter[2] = {"range": {"flag": {"gte": serviceObj.flag}}};
                data.sort[1].flag.order = "asc";
                data.sort[0]['@timestamp'].order = "asc";
                downPageCount += downSize;
                data.from = downPageCount;
                data.size = downSize;
                $scope.ELKGridOptions.dataSource.read();
            }else{
                isUp = false;
                upStop = false;
                upPageCount = 0;
                downPageCount = 0;
                array.length=0;//数据源
                upArray.length=0;//重复数据源
                downArray.length=0;//重复数据源
                isLoadMore=true;//如果为false则不自动加载
                if (serviceObj.logmsg == "1. service begin") {
                    upStop = true;
                }
                data.query.bool.filter[2] = {"range": {"flag": {"gte": serviceObj.flag}}};
                data.sort[1].flag.order = "asc";
                data.sort[0]['@timestamp'].order = "asc";
                data.from = downPageCount;
                data.size = downSize;
                $scope.ELKGridOptions.dataSource.read();
            }
        }
    }

})();
